package com.hqyj.utils;

import org.aspectj.lang.JoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;

// aop切面类
public class LoggingAspect {

    private final Logger logger = LoggerFactory.getLogger(LoggingAspect.class);

//    前置通知
    public void printLogBefore(JoinPoint joinPoint) {
//        获取执行的类名
        String kind = joinPoint.getTarget().getClass().getName();
//        获取类里面的方法名
        String method = joinPoint.getSignature().getName();
//        获取执行时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String localtime = sdf.format((new Date(System.currentTimeMillis())));
//        日志记录
        logger.info("[LOG-INFO][{}] {}.{} 方法开始执行", localtime, kind, method);
        System.out.println(String.format("[LOG-INFO][%s]===%s.%s 方法开始执行",localtime, kind, method));
    }

//    后置通知
    public void printLogAfter(JoinPoint joinPoint, Object result) {
        String kind = joinPoint.getTarget().getClass().getName();
        String method = joinPoint.getSignature().getName();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String localtime = sdf.format((new Date(System.currentTimeMillis())));
        logger.info("[LOG-INFO][{}] {}.{} 方法开始执行完成,返回结果: {}", kind, method, result);
        System.out.println(String.format("[LOG-INFO][%s]===%s.%s 方法执行完成,返回结果: %s", localtime, kind, method, result));
    }

//    异常通知
    public void printLogException(JoinPoint joinPoint, Exception exception){
        String kind = joinPoint.getTarget().getClass().getName();
        String method = joinPoint.getSignature().getName();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String localtime = sdf.format((new Date(System.currentTimeMillis())));
        logger.error("[LOG-ERROR][{}] {}.{} 方法发生异常, 发生的异常为: {}", localtime, kind, method, exception);
        System.out.println(String.format("[LOG-ERROR][%s]===%s.%s 方法发生异常, 发生的异常为: %s",localtime, kind, method, exception));
    }

}
